<?php

declare(strict_types=1);

namespace App\Model\Act;

use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 *  邀请奖励
 */
class InviteRewardLog extends Model
{
    protected $table = 'act_invite_reward_log';

    //充值
    const TYPE_RECHARGE = 1;
    //消费
    const TYPE_CONSUME = 2;
    const TYPE = [
        self::TYPE_RECHARGE => '充值',
        self::TYPE_CONSUME => '收入',
    ];

    /**
     * 添加记录
     */
    static function addRecord($userId = 0, $invitedUserId = 0, $coin = 0, $type = self::TYPE_RECHARGE)
    {
        $model = new self();
        $model->user_id = $userId;
        $model->invited_user_id = $invitedUserId;
        $model->reward_coin = $coin;
        $model->reward_type = $type;
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 获取排行榜
     */
    static function getRank($num = 10)
    {
        $ret = self::select(['user_id', Db::raw('SUM(reward_coin) as coin')])->groupBy('user_id')->orderBy('coin', 'desc')->limit($num)->pluck('coin', 'user_id')->toArray();
        return $ret;
    }

    /**
     * 获取记录
     */
    static function getLog($userId = 0)
    {
        $where = ['user_id' => $userId, 'flag' => 1];
        return self::where($where)->get()->toArray();
    }

    /**
     * 获取记录
     */
    static function getRewardCount($userId = 0, $invitedUserId = 0, $type = self::TYPE_RECHARGE, $offTime = '')
    {
        $where = [
            ['user_id', $userId],
            ['flag', 1]
        ];
        $invitedUserId && $where[] = ['invited_user_id', $invitedUserId];
        $type && $where[] = ['reward_type', $type];
        $offTime && $where[] = ['created_at', '>', $offTime];
        return self::where($where)->count();
    }
}
